package com.lyons.easyweb.modular.dict.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyons.easyweb.core.util.LayuiPageInfo;
import com.lyons.easyweb.exception.BusinessException;
import com.lyons.easyweb.modular.dict.dao.DictMapper;
import com.lyons.easyweb.modular.dict.pojo.Dict;
import com.lyons.easyweb.modular.dict.service.DictService;

/**
 * <p>
 * 字典 服务实现类
 * </p>
 *
 * @author Lyons
 * @since 2021-07-01
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

	@Override
	public LayuiPageInfo deleteById(String id) {

		Dict dict = this.getById(id);
		if (ObjectUtils.isEmpty(dict)) {

			return LayuiPageInfo.fail("数据有误，请传递合法参数 !");
		}

		if (dict.getDictType() == 1) {

			return LayuiPageInfo.fail("系统类型，无法删除，强制删除系统会出问题!");
		}

		removeById(id);

		return LayuiPageInfo.ok("删除成功 !");
	}

	@Override
	public LayuiPageInfo batchDelete(String ids) {

		List<String> idList = Arrays.asList(ids.split(",")).stream().map(e -> {
			if (!ObjectUtils.isEmpty(e)) {
				return e;
			}
			return null;
		}).collect(Collectors.toList());

		int k = 0;
		List<Dict> list = this.listByIds(idList);
		for (Dict e : list) {
			if (e.getDictType() != 1) {
				k++;
				this.removeById(e.getId());
			}
		}
		return LayuiPageInfo.ok("成功删除了 " + k + " 条业务类型字典数据 ！");
	}

	@Override
	public LayuiPageInfo deleteAll() {

		int k = 0;
		List<Dict> list = this.list();

		for (Dict e : list) {
			if (e.getDictType() != 1) {

				k++;
				this.removeById(e.getId());
			}
		}

		return LayuiPageInfo.ok("成功删除了 " + k + " 条业务类型字典数据 ！");
	}

	@Override
	public void insertOrUpdate(Dict dict) {

		if (ObjectUtils.isEmpty(dict.getId())) { // 添加

			this.save(dict);
		} else {

			Dict oldDict = this.getById(dict.getId());

			if (oldDict.getDictType() == 1) {

				throw new BusinessException(4000, "系统类型字典无法修改 !");
			} else {

				this.updateById(dict);
			}
		}
	}

}
